package br.com.simora.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Singleton;

import org.apache.log4j.Logger;

import br.com.simora.radio.Radio;
import br.com.simora.radio.RadioDAO;

@Singleton
public class ManagerFP {
	private static Logger logger = Logger.getLogger(ManagerFP.class);
	@Inject private RadioDAO radioDAO;
	@Inject private Instance<GenericFPRobot> genericRobot;
	
	public void iniciaThreads(){
		List<Radio> listaRadios = (List<Radio>) radioDAO.recuperaTodos(Radio.class);
		GenericFPRobot fpRobot = null;
		ExecutorService executorService = Executors.newFixedThreadPool(100);
		List<GenericFPRobot> lista = new ArrayList<GenericFPRobot>();
		for(Radio radio : listaRadios){
			if(null != radio.getUrl() && !"".equals(radio.getUrl())){
				fpRobot = genericRobot.get();
				fpRobot.setRadio(radio);
				lista.add(fpRobot);
			} else {
				logger.debug(radio.getNome() + ": RADIO SEM URL PARA CAPTURA DE STREAMING");
			}
		}
		System.out.println(lista.size());
		Long tempoEspera = (long) (120000/lista.size());
		System.out.println("tempo entre os robos: " + tempoEspera);
		for(GenericFPRobot robot : lista){
			try {
				executorService.submit(robot);
				Thread.sleep(tempoEspera);
			} catch (InterruptedException e) {
				logger.debug(e.getMessage());
			}
		}
		executorService.shutdown();
	}
}